package com.vivachek.protocol.converts

import com.vivachek.protocol.BaseResult
import com.vivachek.protocol.Parse
import com.vivachek.protocol.enums.Flag
import com.vivachek.protocol.enums.SampleEnums
import com.vivachek.protocol.enums.UnitEnums
import com.vivachek.protocol.utils.ResultUtil

/**
 * @Author: YCB
 * @Time: 2022/9/26 18:42
 * @Email: congbin.yuan@vivachek.com
 * @Description: 历史数据
 *
 */
private const val COMMAND = 221
private const val EXPAND_CODE = 170
private const val LENGTH = 9
internal class HistoryConvert : DataConvert(COMMAND, EXPAND_CODE,LENGTH) {

    override fun parse(data: List<Int>,origin:List<Int>) {
        val date = data.subList(0, 5)
        val glucose = data.subList(5, 7)

        val year = date[0] + 2000
        val month = ResultUtil.fullZero(data[1])
        val day = ResultUtil.fullZero(data[2])
        val hour = ResultUtil.fullZero(data[3])
        val minute = ResultUtil.fullZero(data[4])

        val flag = Flag.convert(data.subList(7, 8).first())
        val ret = when(val sample = SampleEnums.convert(data.last())){
            SampleEnums.GLUCOSE_BLOOD,
            SampleEnums.GLUCOSE_CTRL->{
                var glu = glucose[0] * 100f + glucose[1]
                val value = if (Parse.unit== UnitEnums.MMOL){
                    glu /= 10f
                    ResultUtil.convert(glu)
                }else{
                    glu.toInt().toString()
                }
                BaseResult.Glucose(value,Parse.unit,
                    "${year}-${month}-${day} ${hour}:${minute}:00",
                    flag,sample)
            }
            SampleEnums.KETONES,
            SampleEnums.KETONES_CTRL -> {
                val result = ResultUtil.convert((glucose[0] * 100f + glucose[1]) / 100)
                BaseResult.Ketones(result,UnitEnums.MMOL,
                    "${year}-${month}-${day} ${hour}:${minute}:00",
                    flag,sample)
            }
            SampleEnums.UA,
            SampleEnums.UA_CTRL -> {
                val result = ResultUtil.convert(glucose[0] * 100f + glucose[1])
                BaseResult.UricAcid(result,UnitEnums.UMOL,
                    "${year}-${month}-${day} ${hour}:${minute}:00",
                    flag,sample)
            }
        }
        listener?.historyGlucose(ret)
    }
}